# 对封闭世界场景加密DNS流量分析结果进行分析，分析是什么网站攻击效果好，什么网站攻击效果不好
import json

config = {
    "report_file": "data/close_world/tuned3/report-RF-1000-20220403162414.json",
    "index2domain_file": "/home/chuen/workspace/doh-traffic-trace-analyzer/data/dataset/important/index2domain-SFExtractor-20220402200526-analyzer-shuffled.json",
    "rank_file": "/home/chuen/workspace/website-ranking/chinaz-ranking-20220206.txt"
}
with open(config["index2domain_file"]) as f_in:
    index2domain = json.load(f_in)

with open(config["report_file"], "r") as f_in:
    report = json.load(f_in)["report"]
    
with open(config["rank_file"]) as f_in:
    rank = {}
    for i, data in enumerate(f_in.readlines()):
        rank[data.strip()] = i

def get(i_v, mode:str="top", k:int=10) -> list:
    """
    Args:
        mode: "top" or "last"
        k: top k or last k
    Returns:
        list of domain name.
    """
    domain = []
    if mode == "top":
        i_v = i_v[:k]
    else:
        i_v = i_v[-k:]
    for index, value in i_v:
        domain.append(index2domain[str(index)])
    return domain

def main():

    i_f1 = []
    # print(index2domain)
    for i in report:
        if i not in ["accuracy", "macro avg", "weighted avg"]:
            # print(report[i]["f1-score"])
            i_f1.append((int(float(i)), report[i]["f1-score"]))
    
    i_f1 = sorted(i_f1, key=lambda x: x[1], reverse=True)

    # print(i_f1)
    last = get(i_f1, "last", 500)
    # print("last:", last)

    top = get(i_f1, "top", 500)
    # print("top:", top)

    top_rank, last_rank = [], []
    # print(rank)

    for domain in top:
        top_rank.append(rank[domain])

    print("top ", sum(top_rank))
    for domain in last:
        last_rank.append(rank[domain])
    print("last ", sum(last_rank))




if __name__ == "__main__":
    main()